<template>
  <cu-layout :navProp="{ placeholder: true }">
    <view :class="[`${prefixCls}-checkOut`]">
      <view class="title_box">
        <image :src="$CDN('/common/static/images/icon/f2.png')" alt="" mode="widthFix" />
        <view class="title_text">{{ contract_detail.project_name + contract_detail.room_name }}</view>
      </view>
      <view class="submit-checkout">
        <uv-form :model="form" ref="checkoutForm" :rules="rules">
          <uv-form-item label="合同起租日期" prop="begin_date" borderBottom>
            <!-- <uv-input v-model="contract_detail.begin_date" disabled border="none" /> -->
            <view>{{ contract_detail.begin_date }}</view>
          </uv-form-item>
          <uv-form-item label="合同结束日期" prop="end_date" borderBottom>
            <!-- <uv-input v-model="contract_detail.end_date" disabled border="none" /> -->
            <view>{{ contract_detail.end_date }}</view>
          </uv-form-item>
          <uv-form-item label="退房日期" prop="checkoutDate" borderBottom>
            <uv-input v-model="form.checkoutDate" placeholder="选择退房日期" disabled @click="this.$refs.calendar.open()" border="none" />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-calendar ref="calendar" @confirm="onConfirm" :minDate="minDate" :maxDate="maxDate" color="#046f7e" monthNum="100" :defaultDate="form.checkoutDate || minDate" />

          <uv-form-item label="退房原因" prop="reasonType" borderBottom>
            <uv-input v-model="form.reasonType" placeholder="请选择退房原因" @click="this.$refs.picker.open()" border="none" disabled />
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>

          <uv-picker :columns="reasonOptions" @confirm="reasonConfirm" @cancel="showReasonPicker = false" ref="picker" />

          <uv-form-item v-if="form.reasonType && is_input_text" label="原因" prop="reasonDetail" borderBottom>
            <uv-input v-model="form.reasonDetail" placeholder="请输入原因" type="textarea" border="none" />
          </uv-form-item>

          <uv-form-item v-if="projectSetting.is_attachment_upload == 1" label="上传附件" prop="files" borderBottom>
            <cu-uploader v-model="form.files" :limit="5"></cu-uploader>
          </uv-form-item>

          <view class="out-title-box">
            <image :src="$CDN('/common/static/images/icon/f1.png')" alt="" mode="widthFix" />
            <view class="title">退房须知</view>
          </view>
          <view class="text-line" v-html="projectSetting.checkout_guidelines_content"></view>

          <uv-button style="margin-top: 20px; margin-bottom: 20px" round block color="#046f7e" @click="onSubmit">提交申请</uv-button>
        </uv-form>
      </view>
    </view></cu-layout
  >
</template>
<script>
import { checkoutApplyApi, getProjectIdApi, getSimpleDetailApi } from './api'
export default {
  data() {
    return {
      contract_id: '', // 合同id
      contract_detail: {}, // 合同详情
      form: {
        checkoutDate: '',
        reasonType: '',
        reasonDetail: '',
        files: [],
      },
      showDatePicker: false,
      showReasonPicker: false,
      reasonOptions: [],
      minDate: new Date(),
      maxDate: new Date(2034, 8, 10),
      projectSetting: {},
      is_input_text: false,
      is_input_text_require: false,
      reasonTypeIndex: '',
      fileList: [],
    }
  },
  computed: {
    rules() {
      return {
        checkoutDate: [{ required: true, message: '请选择退房日期' }],
        reasonType: [{ required: true, message: '请选择退房原因' }],
        reasonDetail: [{ required: this.isInputTextRequire, message: '请输入原因' }],
        files: [
          {
            required: this.isUploaderRequired,
            message: '请上传附件',
          },
        ],
      }
    },
    isUploaderRequired() {
      return this.projectSetting?.is_late_checkout_require_attach == 1 && new Date(this.form.checkoutDate) > new Date(this.contract_detail.end_date)
    },
    isInputTextRequire() {
      return this.is_input_text_require
    },
  },
  async onLoad(options) {
    this.contract_id = options.contract_id
    await this.getSimpleDetail()
    await this.getSetting()
  },
  methods: {
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    onConfirm(date) {
      this.showDatePicker = false
      //   this.form.checkoutDate = this.formatDate(date)
      this.form.checkoutDate = date[0]
    },
    onSubmit() {
      console.log(this.form.files)
      //表单校验
      try {
        this.$refs.checkoutForm.validate().then(async () => {
          let params = {
            contract_id: this.contract_id,
            apply_checkout_date: this.form.checkoutDate,
            apply_checkout_reason_options_id: this.settingOption[this.reasonTypeIndex].id,
            select_reason_option_input: this.form.reasonDetail ? this.form.reasonDetail : '',
            attachment: this.form.files.map((item) => {
              return {
                name: item.name,
                url: item.url,
              }
            }),
          }
          console.log('params', params)
          let res = await checkoutApplyApi(params)
          if (res.errcode === 200) {
            uni.showToast({
              title: '提交成功',
              icon: 'none',
            })
            this.$ROUTE.go('/pages/subpackage/contract/checkOutDetail', { contract_id: this.contract_id })
          }
        })
      } catch (e) {
        console.error(e)
      }
    },
    async getSetting() {
      try {
        let res = await getProjectIdApi({ project_id: this.project_id })
        this.projectSetting = res.data
        let date_range = res.data.apply_checkout_date_range_option
        if (date_range >= 0) {
          this.setDateControl(date_range - 1, this.contract_detail.end_date)
        }
        this.settingOption = res.data.options
        const array = res.data.options.map((item, index) => item.option_name)
        this.reasonOptions[0] = array
      } catch (e) {
        console.error(e)
      }
    },
    setDateControl(daysToAdd, target) {
      const currentDate = new Date()
      const targetDate = new Date(target)
      const futureDate = new Date(currentDate)
      futureDate.setDate(currentDate.getDate() + daysToAdd)
      if (futureDate >= targetDate) {
        console.log('不限制日期')
      } else {
        this.minDate.setDate(new Date().getDate() + daysToAdd + 1)
        console.log('限制日期')
      }
    },
    async getSimpleDetail() {
      try {
        let res = await getSimpleDetailApi({ contract_id: this.contract_id })
        this.contract_detail = res.data
        this.contract_detail.begin_date = this.contract_detail.begin_date.split(' ')[0]
        this.contract_detail.end_date = this.contract_detail.end_date.split(' ')[0]
        this.project_id = res.data.project_id
      } catch (e) {
        console.error(e)
      }
    },
    reasonConfirm(value) {
      this.form.reasonType = value.value[0]
      this.reasonTypeIndex = value.indexs[0]
      this.showReasonPicker = false
      this.is_input_text = this.settingOption[this.reasonTypeIndex].is_input_text == 1
      this.is_input_text_require = this.settingOption[this.reasonTypeIndex].is_input_text_require == 1
      console.log(' this.is_input_text_require', this.is_input_text_require)
    },
  },
}
</script>
<style scoped lang="scss">
.#{prefixCls('checkOut')} {
  .title_box {
    width: 100%;
    @include flex-center;
    margin: 20rpx 0;
    image {
      width: 60rpx;
    }
    .title_text {
      font-weight: bold;
    }
  }

  .submit-checkout {
    width: 100%;
    padding: 0 20rpx;
    box-sizing: border-box;
    .out-title-box {
      width: 100%;
      display: flex;
      align-items: center;
      margin-top: 32rpx;
      margin-bottom: 12rpx;
      image {
        width: 60rpx;
      }
      .title {
        font-weight: bold;
      }
    }
    .text-line {
      // font-size: 12px;
    }
  }
  .uv-input {
    background: none !important;
  }
  ::v-deep .uv-form-item__body__left {
    width: 200rpx !important;
  }
}
</style>
